import router, { resetRouter } from '@/router';
import { useAppStoreHook } from '@/store/modules/app';
import { useUserStoreHook } from '@/store/modules/user';
import { usePermissionStoreHook } from "@/store/modules/permission";
function shouldFetchAppConfig(providerKey:string, providerName:string) {
    
    const currentUser = useAppStoreHook().abpConfig.currentUser
  
    if (providerName === 'R') {
      return currentUser.roles.some(role => role === providerKey)
    }
  
    if (providerName === 'U') return currentUser.id === providerKey
  
    return false
  }
  
  export function fetchAppConfig(providerKey:string, providerName:string) {
    const appStore=useAppStoreHook();
    const userStore=useUserStoreHook();
    const permissionStore = usePermissionStoreHook();
    if (shouldFetchAppConfig(providerKey, providerName)) {
        appStore.applicationConfiguration().then(
            abpconfig=>{
                resetRouter(); 
                userStore.setRoles(abpconfig.currentUser.roles);
                const grantedPolicies=abpconfig.auth.grantedPolicies;
                permissionStore.generateRoutes(grantedPolicies).then(
                    accessRoutes=>{
                        accessRoutes.forEach((route) => {
                            router.addRoute(route);
                          });
                    }
                );
             
            }
        );

    }
  }